'''
ppt转pdf - 只可在windows下运行
'''

from win32com import client
import os
import sys
from PyPDF2 import PdfFileReader, PdfFileWriter
from reportlab.lib.units import cm

from reportlab.pdfgen import canvas


name = 'Python自动化办公2'
path = 'C:\\Users\\ayuliao\\Desktop\\ppt\\'
pathpdf = f'{path}自动化办公kPPT2\\'

# ppt转pdf
def ppt2pdf(pptxpath=f'{path}{name}.pptx', pdfpath=f'{pathpdf}{name}.pdf'):
    if not os.path.exists(pdfpath):
        p = client.Dispatch("PowerPoint.Application")
        ppt = p.Presentations.Open(pptxpath, False, False, False)
        ppt.ExportAsFixedFormat(pdfpath, 2, PrintRange=None)
        p.Quit()

# 拆分pdf
def pdf_splitter(start, end, path=f'{pathpdf}{name}.pdf'):
    pdf = PdfFileReader(path)
    pagenum = pdf.getNumPages()
    if end > pagenum:
        return
    pdf_writer = PdfFileWriter()
    for page in range(start, end):
        pdf_writer.addPage(pdf.getPage(page))
    pdfname = f'{pathpdf}{name}_page_{start}_to_{end}.pdf'
    with open(pdfname, 'wb') as out:
        pdf_writer.write(out)
        print(f'Created: {pdfname}')
    return pdfname

# 创建水印
def create_watermark(content):
    #默认大小为21cm*29.7cm
    file_name = "watermark.pdf"
    c = canvas.Canvas(file_name, pagesize = (30*cm, 30*cm))
    #移动坐标原点(坐标系左下为(0,0))
    c.translate(10*cm, 2*cm)
    #设置字体
    c.setFont("Helvetica", 80)
    #指定描边的颜色
    c.setStrokeColorRGB(0, 1, 0)
    #指定填充颜色
    c.setFillColorRGB(0, 1, 0)
    #画一个矩形
    # c.rect(cm, cm, 7*cm, 17*cm, fill=1)
    #旋转45度,坐标系被旋转
    c.rotate(45)
    #指定填充颜色
    c.setFillColorRGB(0.6, 0, 0)
    #设置透明度,1为不透明
    c.setFillAlpha(0.2)
    #画几个文本,注意坐标系旋转的影响
    c.drawString(3*cm, 0*cm, content)
    c.setFillAlpha(0.4)
    #关闭并保存pdf文件
    c.save()
    return file_name


# 添加水印
def add_watermark(input_pdf, output):
    watermark = 'watermark.pdf'
    if not os.path.exists(watermark):
        create_watermark("HackPython")
    watermark_obj = PdfFileReader(watermark)
    watermark_page = watermark_obj.getPage(0)
    pdf_reader = PdfFileReader(input_pdf)
    pdf_writer = PdfFileWriter()
 
    # 给所有页面添加水印
    for page in range(pdf_reader.getNumPages()):
        page = pdf_reader.getPage(page)
        page.mergePage(watermark_page)
        pdf_writer.addPage(page)
 
    with open(output, 'wb') as out:
        pdf_writer.write(out)

def main(i):
    
    pdfname = pdf_splitter(i[0]-1, i[1])
    add_watermark(pdfname, pdfname)

if __name__ == '__main__':
    from multiprocessing import Pool

    # ppt2pdf()
    d = [(1, 26), (27, 46), (47, 57), (58, 85), (86, 110), (111, 140),
    (141, 157), (158, 175), (176, 190), (191, 232), (233, 247), (248, 256),
    (257, 286), (287, 307), (308, 323), (324, 331)]
    with Pool(5) as p:
        p.map(main, d)
